package com.anan;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

/**
 * project_name: easyai-labelimg
 * Author: Anan
 * time: 2025/2/22 12:10
 */


class ImagePanel extends JPanel {
    private BufferedImage image;  // 显示的图片
    public Rectangle tempRect = new Rectangle(); // 临时矩形
    private double scale = 1.0;  // 图片缩放比例
    public List<YoloAnnotation> annotations = new ArrayList<>();  //目标检测框信息列表



    public void setImage(BufferedImage image) {
        this.image = image;
        scale = Math.min(1.0, Math.min(
                800.0 / image.getWidth(),
                600.0 / image.getHeight()
        ));
        setPreferredSize(new Dimension(
                (int)(image.getWidth() * scale),
                (int)(image.getHeight() * scale)
        ));
        revalidate();
        repaint();
    }

    public void setTempRect(Rectangle rect) {
        this.tempRect = rect;
    }


    public Rectangle getActualRect(Rectangle displayRect) {
        if (image == null) return null;
        return new Rectangle(
                (int)(displayRect.x / scale),
                (int)(displayRect.y / scale),
                (int)(displayRect.width / scale),
                (int)(displayRect.height / scale)
        );
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            Graphics2D g2 = (Graphics2D)g;
            g2.scale(scale, scale);
            g2.drawImage(image, 0, 0, null);

            // 绘制已有标注
            g2.setColor(Color.RED);
            for (YoloAnnotation ann : annotations) {
                g2.drawRect(ann.x, ann.y, ann.width, ann.height);
                g2.drawString(ann.classId, ann.x, ann.y-5);
            }
//            // 绘制临时矩形
            if (tempRect.x >0) {
                g2.setColor(Color.GREEN);
                Rectangle actualRect = getActualRect(tempRect);
                g2.drawRect(actualRect.x, actualRect.y, actualRect.width, actualRect.height);
            }
        }
    }
}
